package com.jiechuang.user.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiechuang.common.bean.Menu;
import com.jiechuang.common.bean.addOrUpdate.MenuAddOrUpdate;
import com.jiechuang.common.exception.AddException;
import com.jiechuang.common.exception.NotNullException;
import com.jiechuang.user.dto.MenuQueryInfo;
import com.jiechuang.user.mapper.MenuMapper;
import com.jiechuang.user.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<Menu> getMenuListByRoleCodes(List<String> roleCodes) {
        if(CollectionUtils.isEmpty(roleCodes)){
            throw new NotNullException("未查询到该用户的角色");
        }
        //查询所有菜单
        List<Menu> menuParent = menuMapper.getMenuListByRoleCodes(roleCodes);
        //整理菜单层级
        menuParent=getMenuClass(menuParent);
        return menuParent;
    }

    @Override
    public PageInfo<Menu> getMenuAllList(MenuQueryInfo menuQueryInfo) {
        PageHelper.startPage(menuQueryInfo.getPageNum(), menuQueryInfo.getPageSize());
        List<Menu> menuAllList = menuMapper.getMenuAllList(menuQueryInfo);
        return new PageInfo<>(menuAllList);
    }

    @Override
    public void addMenu(MenuAddOrUpdate menuAddOrUpdate) {
        int i=menuMapper.addMenu(menuAddOrUpdate);
        if(i==0){
            throw new AddException("新增失败");
        }
    }

    @Override
    public Menu getMenu(Integer id) {
        return menuMapper.getMenu(id);
    }

    private List<Menu> getMenuClass(List<Menu> menuParent) {
        //获取一级菜单
        List<Menu> menu1 = menuParent.stream().filter(m1 -> m1.getParentId() == 0).collect(Collectors.toList());
        menu1.forEach(m1->{
            //获取二级菜单
            List<Menu> menu2 = menuParent.stream().filter(m2 -> m2.getParentId() == m1.getId()).collect(Collectors.toList());
            m1.setChildren(menu2);
        });
        return menu1;
    }
}
